<template>
  <div class="app-container">
    <template>
      <div class="hidden-md-and-up">
        <el-alert title="如若不适应手机端操作，建议使用电脑操作" type="warning" />
      </div>
    </template>
    <div class="table-container">
      <!-- 查询条件 -->
      <div style="padding-bottom:20px; display: flex;">
        <div style="width: 260px;">
          <label>姓名</label>
          <el-input v-model="searchForm.name" placeholder="姓名" size="medium" class="query-input" style="width: 160px;" />
        </div>
        <div style="width: 260px;">
          <label>所属机构</label>
          <el-select
            v-model="searchForm.dept"
            :loading="deptLoading"
            placeholder="请选择所属机构"
            filterable
            clearable
            size="medium"
            style="width: 160px;"
            @focus="fetchDeptData"
          >
            <el-option v-for="item in dept_options" :key="item.deptID" :label="item.deptName" :value="item.deptID" />
          </el-select>
        </div>
        <div style="width: 260px;">
          <label>工号</label>
          <el-input v-model="searchForm.account" placeholder="工号" size="medium" class="query-input" style="width: 160px;" />
        </div>
        <el-button type="primary" size="medium" class="query-button" @click="handleSearch">查询</el-button>
        <el-button type="primary" size="medium" plain @click="addUser">用户添加</el-button>
        <el-button type="primary" size="medium" plain @click="refreshUser">同步最新数据</el-button>
      </div>
      <!-- 用户列表 -->
      <el-table
        v-loading="userListLoading"
        :data="userList"
        element-loading-text="Loading....."
        border
        fit
      >
        <el-table-column type="selection" align="center" width="100" />
        <el-table-column prop="name" align="left" label="姓名" width="150" />
        <el-table-column prop="account" align="center" label="工号" width="150" />
        <el-table-column prop="deptName" align="center" label="所属机构" width="250" />

        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :current-page="p1_page"
          :page-sizes="[10,20,50,100]"
          :page-size="p1_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="p1_total"
          @size-change="p1_sizechange"
          @current-change="p1_currentchange"
        />
      </div>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false">
        <el-form ref="addForm" :model="addForm" label-position="top" label-width="120px" autocomplete="off">
          <el-row>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="addForm.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="工号" prop="account">
                <el-input v-model="addForm.account" placeholder="请输入工号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="所属机构" prop="dept">
                <el-select
                  v-model="addForm.dept"
                  :loading="deptLoading"
                  placeholder="请选择所属机构"
                  filterable
                  clearable
                  @focus="fetchDeptData"
                >
                  <el-option v-for="item in dept_options" :key="item.deptID" :label="item.deptName" :value="item.deptID" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="权限" prop="role">
                <el-select
                  v-model="addForm.role"
                  placeholder="请选择权限"
                  filterable
                  clearable
                >
                  <el-option v-for="item in role_options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">保存</el-button>
        </div>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false">
        <el-form ref="editForm" :model="editForm" label-position="top" label-width="120px" autocomplete="off">
          <el-row>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="工号" prop="account">
                <el-input v-model="editForm.account" placeholder="请输入工号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="所属机构" prop="deptName">
                <el-select
                  v-model="editForm.deptName"
                  :value-key="editForm.dept"
                  :loading="deptLoading"
                  placeholder="请选择所属机构"
                  filterable
                  clearable
                  @focus="fetchDeptData"
                  @change="handleDeptChange"
                >
                  <el-option
                    v-for="item in dept_options"
                    :key="item.deptID"
                    :label="item.deptName"
                    :value="item.deptName"
                    :data-id="item.deptID"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="权限" prop="role">
                <el-select
                  v-model="editForm.role"
                  placeholder="请选择权限"
                  filterable
                  clearable
                >
                  <el-option v-for="item in role_options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate(editForm)">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList, addUser, updateUser, deleteUser, getDepartments, getDepts, refreshUser } from '@/api/system'
import { Message, MessageBox } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      searchForm: {
        name: '',
        dept: '',
        account: ''
      },
      deptList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        id: '',
        name: '',
        account: '',
        dept: '',
        deptName: '',
        role: ''
      },
      editForm: {
        id: '',
        name: '',
        account: '',
        dept: '',
        deptName: '',
        role: ''
      },
      userList: [],
      dept_options: [],
      // 权限选项列表 - 固定选项
      role_options: [
        { value: '院级审核员', label: '院级审核员' },
        { value: '校级审核员', label: '校级审核员' },
        { value: '院级教师', label: '院级教师' }
      ],
      userListLoading: false,
      deptLoading: false,
      p1_size: 10,
      p1_page: 1,
      p1_total: 0
    }
  },
  computed: {
    ...mapGetters([
      'uid',
      'roles',
      'name'
    ]),
    MyPaperPost() {
      return {
        id: this.uid,
        account: this.searchForm.account,
        dept: this.searchForm.dept,
        name: this.searchForm.name,
        pageNum: this.p1_page,
        pageSize: this.p1_size,
        roles: this.roles
      }
    }
  },
  created() {
    this.fetchUserData()
  },
  methods: {
    fetchDeptData() {
      if (this.dept_options.length === 0) {
        this.deptLoading = true
        getDepts().then(response => {
          if (response.code === 200) {
            this.dept_options = response.data
            this.deptLoading = false
          }
        })
      }
    },
    handleDeptChange(selectedName) {
      const selectedDept = this.dept_options.find(item => item.deptName === selectedName)
      if (selectedDept) {
        this.editForm.dept = selectedDept.deptID
        this.editForm.deptName = selectedName
      }
    },
    p1_sizechange(newsize) {
      this.p1_size = newsize
      this.p1_page = 1
      this.fetchUserData()
    },
    p1_currentchange(newpage) {
      this.p1_page = newpage
      this.fetchUserData()
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    addUser() {
      this.addDialogVisible = true
      this.resetForm('addForm')
    },
    refreshUser() {
      // 添加加载动画
      const loading = this.$loading({
        lock: true,
        text: '数据同步中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      refreshUser().then(response => {
        // 关闭加载动画
        loading.close()
        if (response.code === 200) {
          Message.success('刷新成功')
          this.fetchUserData()
        } else {
          Message.error(response.message || '刷新失败')
        }
      }).catch(error => {
        // 异常时也关闭加载动画
        loading.close()
        console.error('刷新失败', error)
        Message.error('刷新失败')
      })
    },
    // 获取用户列表
    fetchUserData() {
      this.userListLoading = true
      getUserList(this.MyPaperPost).then(response => {
        if (response.code === 200) {
          this.userList = response.data.list
          this.p1_total = response.data.total
          this.userListLoading = false
        }
      })
    },
    // 获取所属机构数据
    async getDepartments() {
      try {
        const response = await getDepartments()
        if (response.code === 200) {
          this.deptList = response.data
        } else {
          Message.error(response.message || '获取所属机构数据失败')
        }
      } catch (error) {
        console.error('获取所属机构数据失败', error)
        Message.error('获取所属机构数据失败')
      }
    },
    // 处理查询
    handleSearch() {
      this.p1_page = 1
      this.fetchUserData()
    },
    // 保存新增用户
    handleAdd() {
      addUser(this.addForm).then(response => {
        if (response.code === 200) {
          Message.success('保存成功')
          this.addDialogVisible = false
          this.fetchUserData()
        }
      })
    },
    // 打开编辑对话框
    openEditDialog(row) {
      this.editDialogVisible = true
      this.editForm = {
        id: row.id,
        name: row.name,
        account: row.account,
        dept: row.deptID || row.dept,
        deptName: row.deptName,
        role: row.role || row.permission || ''
      }
      console.log('编辑用户数据:', row, this.editForm)
    },
    // 保存更新用户
    handleUpdate(formdata) {
      updateUser(formdata).then(response => {
        if (response.code === 200) {
          Message.success('用户更新成功')
          this.editDialogVisible = false
          this.fetchUserData()
        } else {
          Message.error(response.message || '更新失败')
        }
      }).catch(error => {
        console.error('更新用户失败', error)
        Message.error('更新用户失败')
      })
    },
    // 处理删除用户
    handleDelete(row) {
      console.log(row.id)
      MessageBox.confirm('确定要删除该用户吗？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(response => {
          if (response.code === 200) {
            Message.success('删除成功')
            this.fetchUserData()
          } else {
            Message.error(response.message || '删除失败')
          }
        }).catch(error => {
          console.error('删除用户失败', error)
          Message.error('删除用户失败')
        })
      }).catch(() => {
        Message.info('已取消删除')
      })
    }
  }
}
</script>
<style lang="scss">
.el-form{
  margin-left: 40px;
  .el-input, .el-select{
    width: 300px;
  }
}
.el-tag + .el-tag {
  margin: 10px 10px;
}
.margin-top {
  margin-top: 50px;
}
@media screen and (max-width:600px) {
  .el-dialog{
    width: 100%!important;
  }
  .el-form{
    margin-left: 25px;
  }
}
.query-container {
  display: flex;
  align-items: center;
}
.query-input,
.query-select {
  margin-right: 10px;
}
.query-button {
  margin-left: 10px;
}
</style>
